import React, { memo, useEffect, useState, useMemo } from 'react';
import { 
  Card, 
  Button, 
  Row, 
  Col, 
  Space, 
  Typography, 
  Divider,
  Modal,
  message,
  Spin,
  Tabs,
  Badge,
  Select,
  DatePicker,
  Switch,
  Tooltip
} from 'antd';
import { 
  PlusOutlined, 
  CalendarOutlined, 
  ClockCircleOutlined,
  EyeOutlined,
  EditOutlined,
  DeleteOutlined,
  ExclamationCircleOutlined,
  UserOutlined,
  BookOutlined,
  WarningOutlined,
  CheckCircleOutlined
} from '@ant-design/icons';
import { useSearchParams } from 'react-router-dom';
import dayjs from 'dayjs';
import { 
  DailyScheduleView,
  WeeklyCalendarView,
  ScheduleTemplateForm,
  ScheduleInstanceCard,
  ScheduleConflictDialog,
  MixedScheduleView
} from '@/components/business/schedule';
import { 
  useScheduleManagement, 
  useScheduleView,
  useScheduleStats,
  useScheduleConflict
} from '@/store/schedule';
import { useStudentManagement } from '@/store/student';
import { useCourseManagement } from '@/store/course';
import { getCurrentDate, formatDateForDisplay } from '@/utils/date';
import type { IScheduleTemplate, IScheduleInstance } from '@/types/schedule';
import type { ScheduleViewTypeEnum } from '@/types/schedule';
import { ConflictTypeEnum } from '@/types/schedule';
import styles from './SchedulePage.module.css';

const { Title, Text } = Typography;
const { TabPane } = Tabs;
const { Option } = Select;
const { RangePicker } = DatePicker;
const { confirm } = Modal;

/**
 * 课表管理页面组件
 * @description 提供课表的查看、管理和冲突检测功能
 */
const SchedulePage: React.FC = memo(() => {
  const [searchParams, setSearchParams] = useSearchParams();
  
  // 本地状态
  const [showTemplateForm, setShowTemplateForm] = useState(false);
  const [templateFormMode, setTemplateFormMode] = useState<'create' | 'edit'>('create');
  const [currentTemplate, setCurrentTemplate] = useState<IScheduleTemplate | null>(null);
  const [showConflictDialog, setShowConflictDialog] = useState(false);
  const [activeTab, setActiveTab] = useState('calendar');
  const [selectedStudents, setSelectedStudents] = useState<string[]>([]);
  const [showMixedView, setShowMixedView] = useState(false);

  // 状态管理
  const {
    templates,
    instances,
    addTemplate,
    updateTemplate,
    deleteTemplate,
    generateInstances,
    cancelInstance,
    completeInstance,
    refresh,
    openInstanceDetail
  } = useScheduleManagement();

  const {
    viewType,
    selectedDate,
    setViewType,
    setSelectedDate
  } = useScheduleView();

  const {
    templateStats,
    instanceStats
  } = useScheduleStats();

  const {
    conflicts,
    checkTemplateConflict,
    clearConflicts
  } = useScheduleConflict();

  const {
    students,
    isLoading: studentsLoading,
    fetchStudents
  } = useStudentManagement();

  const {
    courses,
    fetchCourses
  } = useCourseManagement();

  // 初始化数据
  useEffect(() => {
    const initializeData = async () => {
      try {
        await Promise.all([
          refresh(),
          fetchStudents(),
          fetchCourses()
        ]);
      } catch (error) {
        console.error('初始化课表页面数据失败:', error);
        message.error('加载数据失败，请刷新页面重试');
      }
    };

    initializeData();
  }, []); // 移除函数依赖，避免无限循环

  // 处理URL参数
  useEffect(() => {
    const action = searchParams.get('action');
    const templateId = searchParams.get('templateId');
    const date = searchParams.get('date');
    const studentId = searchParams.get('student');

    if (action === 'create') {
      handleCreateTemplate();
    } else if (action === 'edit' && templateId) {
      const template = templates.find(t => t.id === templateId);
      if (template) {
        handleEditTemplate(template);
      }
    }

    if (date) {
      setSelectedDate(date);
    }

    if (studentId) {
      setSelectedStudents([studentId]);
      setShowMixedView(false);
    }
  }, [searchParams, templates, setSelectedDate]);

  // 课表统计
  const scheduleStats = useMemo(() => {
    const today = getCurrentDate();
    const todaySchedules = instances.filter(instance => instance.date === today);
    const activeTemplates = templates.filter(template => template.status === 1);
    
    return {
      totalTemplates: templates.length,
      activeTemplates: activeTemplates.length,
      totalInstances: instances.length,
      todayInstances: todaySchedules.length,
      completedToday: todaySchedules.filter(instance => instance.status === 2).length,
      upcomingInstances: instances.filter(instance => 
        instance.date > today && instance.status === 1
      ).length,
      conflictCount: conflicts.length
    };
  }, [templates, instances, conflicts]);

  // 获取学生姓名
  const getStudentName = (studentId: string): string => {
    const student = students.find(s => s.id === studentId);
    return student?.name || '未知学生';
  };

  // 获取课程名称
  const getCourseName = (courseId: string): string => {
    const course = courses.find(c => c.id === courseId);
    return course?.name || '未知课程';
  };

  // 创建课程模板
  const handleCreateTemplate = () => {
    setCurrentTemplate(null);
    setTemplateFormMode('create');
    setShowTemplateForm(true);
    setSearchParams({});
  };

  // 编辑课程模板
  const handleEditTemplate = (template: IScheduleTemplate) => {
    setCurrentTemplate(template);
    setTemplateFormMode('edit');
    setShowTemplateForm(true);
  };

  // 删除课程模板
  const handleDeleteTemplate = (template: IScheduleTemplate) => {
    const relatedInstances = instances.filter(instance => 
      instance.templateId === template.id
    );

    confirm({
      title: '确认删除课程模板',
      icon: <ExclamationCircleOutlined />,
      content: (
        <div>
          <p>确定要删除课程模板吗？</p>
          {relatedInstances.length > 0 && (
            <p style={{ color: '#ff4d4f', fontSize: '12px' }}>
              删除后相关的 {relatedInstances.length} 个课程实例也将被删除，此操作不可恢复。
            </p>
          )}
        </div>
      ),
      okText: '确认删除',
      okType: 'danger',
      cancelText: '取消',
      onOk: async () => {
        try {
          await deleteTemplate(template.id);
          message.success('课程模板删除成功');
        } catch (error) {
          console.error('删除课程模板失败:', error);
          message.error('删除课程模板失败，请重试');
        }
      }
    });
  };

  // 完成课程实例
  const handleCompleteInstance = async (instance: IScheduleInstance) => {
    try {
      await completeInstance(instance.id);
      message.success('课程标记为已完成');
    } catch (error) {
      console.error('完成课程失败:', error);
      message.error('操作失败，请重试');
    }
  };

  // 取消课程实例
  const handleCancelInstance = (instance: IScheduleInstance) => {
    confirm({
      title: '确认取消课程',
      icon: <ExclamationCircleOutlined />,
      content: `确定要取消 ${formatDateForDisplay(instance.date)} 的课程吗？`,
      okText: '确认取消',
      okType: 'danger',
      cancelText: '取消',
      onOk: async () => {
        try {
          await cancelInstance(instance.id, '用户手动取消');
          message.success('课程已取消');
        } catch (error) {
          console.error('取消课程失败:', error);
          message.error('取消课程失败，请重试');
        }
      }
    });
  };

  // 模板表单提交
  const handleTemplateFormSubmit = async (formData: any) => {
    try {
      // 检查冲突
      await checkTemplateConflict(formData);
      
      if (conflicts && conflicts.length > 0) {
        setShowConflictDialog(true);
        return;
      }

      if (templateFormMode === 'create') {
        await addTemplate(formData);
        message.success('课程模板添加成功');
      } else {
        await updateTemplate(currentTemplate!.id, formData);
        message.success('课程模板更新成功');
      }
      
      setShowTemplateForm(false);
      setCurrentTemplate(null);
    } catch (error) {
      console.error('保存课程模板失败:', error);
      message.error(templateFormMode === 'create' ? '添加课程模板失败' : '更新课程模板失败');
    }
  };

  // 冲突解决
  const handleConflictResolve = async (resolution: any) => {
    try {
      // 清除冲突信息
      clearConflicts();
      setShowConflictDialog(false);
      message.success('冲突已解决');
    } catch (error) {
      console.error('解决冲突失败:', error);
      message.error('解决冲突失败，请重试');
    }
  };

  // 切换视图模式
  const handleViewModeChange = (mode: ScheduleViewTypeEnum) => {
    setViewType(mode);
  };

  // 学生选择变化
  const handleStudentSelectionChange = (studentIds: string[]) => {
    setSelectedStudents(studentIds);
  };

  // 混合视图切换
  const handleMixedViewToggle = (enabled: boolean) => {
    setShowMixedView(enabled);
    if (!enabled) {
      setSelectedStudents([]);
    }
  };

  const isLoading = false;

  return (
    <div className={styles.schedulePage}>
      {/* 页面头部 */}
      <div className={styles.pageHeader}>
        <div className={styles.headerContent}>
          <div className={styles.titleSection}>
            <Title level={2} className={styles.pageTitle}>
              <CalendarOutlined /> 课表管理
            </Title>
            <Text type="secondary">
              管理课程安排，查看课表，检测时间冲突
            </Text>
          </div>
          <div className={styles.actionSection}>
            <Space>
              <Tooltip title="混合课表显示">
                <Switch
                  checked={showMixedView}
                  onChange={handleMixedViewToggle}
                  checkedChildren="混合"
                  unCheckedChildren="单独"
                />
              </Tooltip>
              {showMixedView && (
                <Select
                  mode="multiple"
                  placeholder="选择学生"
                  style={{ minWidth: 200 }}
                  value={selectedStudents}
                  onChange={handleStudentSelectionChange}
                  maxTagCount={2}
                >
                  {students.map(student => (
                    <Option key={student.id} value={student.id}>
                      {student.name}
                    </Option>
                  ))}
                </Select>
              )}
              <Button 
                type="primary" 
                icon={<PlusOutlined />}
                onClick={handleCreateTemplate}
              >
                安排课程
              </Button>
            </Space>
          </div>
        </div>

        {/* 统计信息 */}
        <Row gutter={16} className={styles.statsRow}>
          <Col span={4}>
            <Card className={styles.statCard}>
              <div className={styles.statContent}>
                <div className={styles.statNumber}>{templateStats.total}</div>
                <div className={styles.statLabel}>课程模板</div>
              </div>
            </Card>
          </Col>
          <Col span={4}>
            <Card className={styles.statCard}>
              <div className={styles.statContent}>
                <div className={styles.statNumber} style={{ color: '#52c41a' }}>
                  {templateStats.active}
                </div>
                <div className={styles.statLabel}>进行中</div>
              </div>
            </Card>
          </Col>
          <Col span={4}>
            <Card className={styles.statCard}>
              <div className={styles.statContent}>
                <div className={styles.statNumber} style={{ color: '#1890ff' }}>
                  {scheduleStats.todayInstances}
                </div>
                <div className={styles.statLabel}>今日课程</div>
              </div>
            </Card>
          </Col>
          <Col span={4}>
            <Card className={styles.statCard}>
              <div className={styles.statContent}>
                <div className={styles.statNumber} style={{ color: '#52c41a' }}>
                  {scheduleStats.completedToday}
                </div>
                <div className={styles.statLabel}>已完成</div>
              </div>
            </Card>
          </Col>
          <Col span={4}>
            <Card className={styles.statCard}>
              <div className={styles.statContent}>
                <div className={styles.statNumber} style={{ color: '#faad14' }}>
                  {scheduleStats.upcomingInstances}
                </div>
                <div className={styles.statLabel}>即将到来</div>
              </div>
            </Card>
          </Col>
          <Col span={4}>
            <Card className={styles.statCard}>
              <div className={styles.statContent}>
                <div className={styles.statNumber} style={{ color: scheduleStats.conflictCount > 0 ? '#ff4d4f' : '#52c41a' }}>
                  {scheduleStats.conflictCount}
                </div>
                <div className={styles.statLabel}>时间冲突</div>
              </div>
            </Card>
          </Col>
        </Row>
      </div>

      <Divider />

      {/* 主要内容 */}
      <div className={styles.pageContent}>
        <Spin spinning={isLoading}>
          <Tabs 
            activeKey={activeTab} 
            onChange={setActiveTab}
            className={styles.contentTabs}
          >
            <TabPane 
              tab={
                <span>
                  <CalendarOutlined />
                  课表视图
                </span>
              } 
              key="calendar"
            >
              <Card className={styles.calendarCard}>
                {/* 视图控制 */}
                <div className={styles.viewControls}>
                  <Row justify="space-between" align="middle">
                    <Col>
                      <Space>
                        <Select
                          value={viewType}
                          onChange={handleViewModeChange}
                          style={{ width: 120 }}
                        >
                          <Option value="day">日视图</Option>
                          <Option value="week">周视图</Option>
                        </Select>
                        {viewType === 'day' && (
                          <DatePicker
                            value={dayjs(selectedDate)}
                            onChange={(date) => setSelectedDate(date?.format('YYYY-MM-DD') || getCurrentDate())}
                          />
                        )}
                        {viewType === 'week' && (
                          <DatePicker
                            picker="week"
                            value={dayjs(selectedDate)}
                            onChange={(date) => setSelectedDate(date?.startOf('week').format('YYYY-MM-DD') || getCurrentDate())}
                          />
                        )}
                      </Space>
                    </Col>
                    <Col>
                      <Space>
                        <Button
                          onClick={() => {
                            const today = getCurrentDate();
                            setSelectedDate(today);
                          }}
                        >
                          今天
                        </Button>
                      </Space>
                    </Col>
                  </Row>
                </div>

                {/* 课表内容 */}
                <div className={styles.scheduleContent}>
                  {showMixedView && selectedStudents.length > 0 ? (
                    <MixedScheduleView
                      selectedStudents={selectedStudents}
                      scheduleInstances={instances}
                      students={students}
                      courses={courses}
                      onStudentToggle={(studentId) => {
                        const newSelection = selectedStudents.includes(studentId)
                          ? selectedStudents.filter(id => id !== studentId)
                          : [...selectedStudents, studentId];
                        setSelectedStudents(newSelection);
                      }}
                      onInstanceClick={(instance) => {
                        // 处理课程实例点击
                        openInstanceDetail(instance);
                      }}
                    />
                  ) : viewType === 'day' ? (
                    <DailyScheduleView
                      date={selectedDate}
                      scheduleInstances={instances.filter(instance => instance.date === selectedDate)}
                      students={students}
                      courses={courses}
                      viewMode="single"
                      selectedStudents={[]}
                      onInstanceClick={(instance) => {
                        // 处理实例点击
                      }}
                      onDateChange={setSelectedDate}
                    />
                  ) : (
                    <WeeklyCalendarView
                      weekStartDate={selectedDate}
                      scheduleInstances={instances}
                      students={students}
                      courses={courses}
                      selectedStudents={[]}
                      onDateClick={setSelectedDate}
                      onInstanceClick={(instance) => {
                        // 处理实例点击
                      }}
                      onWeekChange={setSelectedDate}
                    />
                  )}
                </div>
              </Card>
            </TabPane>

            <TabPane 
              tab={
                <span>
                  <ClockCircleOutlined />
                  课程模板
                  <Badge count={templates.length} showZero style={{ marginLeft: 8 }} />
                </span>
              } 
              key="templates"
            >
              <Card className={styles.templatesCard}>
                <Row gutter={[16, 16]}>
                  {templates.map(template => {
                    const relatedInstances = instances.filter(instance => 
                      instance.templateId === template.id
                    );
                    return (
                      <Col xs={24} sm={12} lg={8} xl={6} key={template.id}>
                        <Card
                          className={styles.templateCard}
                          actions={[
                            <EditOutlined 
                              key="edit" 
                              onClick={() => handleEditTemplate(template)} 
                            />,
                            <DeleteOutlined 
                              key="delete" 
                              onClick={() => handleDeleteTemplate(template)} 
                            />
                          ]}
                        >
                          <div className={styles.templateContent}>
                            <div className={styles.templateHeader}>
                              <Text strong>{getCourseName(template.courseId)}</Text>
                              <Badge 
                                status={template.status === 1 ? 'processing' : 'default'}
                                text={template.status === 1 ? '进行中' : '已完成'}
                              />
                            </div>
                            <div className={styles.templateInfo}>
                              <p><UserOutlined /> {getStudentName(template.studentId)}</p>
                              <p><ClockCircleOutlined /> {template.startTime} - {template.endTime}</p>
                              <p><CalendarOutlined /> 每周{['', '一', '二', '三', '四', '五', '六', '日'][template.dayOfWeek]}</p>
                              <p>进度: {template.completedCount}/{template.totalCount}</p>
                            </div>
                          </div>
                        </Card>
                      </Col>
                    );
                  })}
                </Row>
              </Card>
            </TabPane>

            <TabPane 
              tab={
                <span>
                  <WarningOutlined />
                  冲突检测
                  {scheduleStats.conflictCount > 0 && (
                    <Badge count={scheduleStats.conflictCount} style={{ marginLeft: 8 }} />
                  )}
                </span>
              } 
              key="conflicts"
            >
              <Card className={styles.conflictsCard}>
                {conflicts.length > 0 ? (
                  <div className={styles.conflictsList}>
                    {conflicts.map((conflict, index) => (
                      <Card key={index} className={styles.conflictItem}>
                        <div className={styles.conflictContent}>
                          <div className={styles.conflictHeader}>
                            <WarningOutlined style={{ color: '#ff4d4f' }} />
                            <Text strong>时间冲突</Text>
                          </div>
                          <div className={styles.conflictDetails}>
                            <p>冲突类型: {conflict.type}</p>
                            <p>涉及项目: {conflict.conflictingItems?.length || 0} 个</p>
                            <p>冲突类型: {conflict.type}</p>
                          </div>
                        </div>
                      </Card>
                    ))}
                  </div>
                ) : (
                  <div className={styles.noConflicts}>
                    <CheckCircleOutlined style={{ fontSize: 48, color: '#52c41a' }} />
                    <Title level={4}>暂无时间冲突</Title>
                    <Text type="secondary">所有课程安排都没有时间冲突</Text>
                  </div>
                )}
              </Card>
            </TabPane>
          </Tabs>
        </Spin>
      </div>

      {/* 课程模板表单模态框 */}
      <Modal
        title={templateFormMode === 'create' ? '安排课程' : '编辑课程安排'}
        open={showTemplateForm}
        onCancel={() => {
          setShowTemplateForm(false);
          setCurrentTemplate(null);
          setSearchParams({});
        }}
        footer={null}
        width={700}
        destroyOnHidden
      >
        <ScheduleTemplateForm
          template={currentTemplate || undefined}
          students={students}
          courses={courses}
          visible={showTemplateForm}
          mode={templateFormMode}
          onSubmit={handleTemplateFormSubmit}
          onCancel={() => {
            setShowTemplateForm(false);
            setCurrentTemplate(null);
            setSearchParams({});
          }}
        />
      </Modal>

      {/* 冲突处理对话框 */}
      <ScheduleConflictDialog
        conflicts={conflicts.map(conflict => ({
          type: (() => {
            switch (conflict.type) {
              case ConflictTypeEnum.TIME_OVERLAP:
              case ConflictTypeEnum.SAME_TIME:
                return 'time' as const;
              case ConflictTypeEnum.TEACHER_CONFLICT:
                return 'teacher' as const;
              case ConflictTypeEnum.LOCATION_CONFLICT:
                return 'classroom' as const;
              default:
                return 'time' as const;
            }
          })(),
          message: conflict.message,
          conflictInstances: [], // TODO: 转换 conflictingItems 为 conflictInstances
          severity: 'warning' as const
        }))}
        visible={showConflictDialog}
        onResolve={handleConflictResolve}
        onCancel={() => setShowConflictDialog(false)}
      />
    </div>
  );
});

SchedulePage.displayName = 'SchedulePage';

export default SchedulePage;